package com.example.yls.listview_sqlite;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;

import java.io.File;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity
        implements IOnDataChangeListener{
private Button btnAdd;
private ListView lvStu;
private ArrayList<Student> studentArrayList = new ArrayList<>();
private StuAdapter adapter;
private ImageView ivSearch;
private EditText edtKey;
    private ContentValues contentValues;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findViews();

     /*   initStudentArrayList();*/

        readDataFromDB();


        adapter = new StuAdapter(MainActivity.this,studentArrayList,MainActivity.this);
        readDataFromDB();
       lvStu.setAdapter(adapter);
lvStu.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
         Student student = studentArrayList.get(i);
         Intent intent = new Intent();
         intent.setClass(MainActivity.this,EditActivity.class);
         intent.putExtra("STUNO",student.getStuno());
        intent.putExtra("NAME",student.getStuname());
        intent.putExtra("AGE",student.getStuage());

        startActivityForResult(intent,1002);

    }
});



    }

    private void readDataFromDB() {
        String path = getFilesDir().getAbsolutePath() + File.separator + "stu.db";
        SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(path, null);

        String sql = "create table if not exists student (stuno varchar(20), stuname varchar(20), stuage int)";
         db.execSQL(sql);

        studentArrayList.clear();
         Cursor cursor = db.query("student",null,null,
                 null,null,null,null,null);

         if(cursor != null && cursor.getCount() > 0){



         for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
             String stuno = cursor.getString(0);
             String stuname = cursor.getString(1);
             int stuage = cursor.getInt(2);

        Student student = new Student(stuno,stuname,stuage);
        studentArrayList.add(student);
}

         }

        cursor.close();
        db.close();
    }

/*    private void initStudentArrayList() {
        studentArrayList.add(new Student("1001","李白",33));
        studentArrayList.add(new Student("1002","杜甫",24));

        studentArrayList.add(new Student("1003","杜牧",43));

        studentArrayList.add(new Student("1004","李清照",41));

        studentArrayList.add(new Student("1005","张爱玲",35));

    }*/

    public void findViews() {
        btnAdd = findViewById(R.id.btn_add);
        lvStu = findViewById(R.id.lv_Stu);

        btnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setClass(MainActivity.this,AddActivity.class);
                startActivityForResult(intent,1001);
            }
        });
        edtKey = findViewById(R.id.edt_key);
        ivSearch = findViewById(R.id.iv_search);
        ivSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String key = edtKey.getText().toString();
                searchFromDB(key);
            }
        });

    }

    private void searchFromDB(String key) {
        String where = "stuname like '%"+key+"%' OR stuno like '%"+key+"%' OR stuage = '" + key + "'";

        String path = getFilesDir().getAbsolutePath() + File.separator + "stu.db";
        SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(path,null);


        studentArrayList.clear();
        Cursor cursor = db.query("student",null,where,
                null,null,null,null,null);

        if(cursor != null && cursor.getCount() > 0){



        for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
            String stuno = cursor.getString(0);
            String stuname = cursor.getString(1);
            int stuage = cursor.getInt(2);

            Student student = new Student(stuno,stuname,stuage);
            studentArrayList.add(student);
        }
        }
        adapter.notifyDataSetChanged();
        cursor.close();
        db.close();



    }

    protected void onActivityResult(int requestCode,int resultCode,Intent data){
        if(resultCode == 2001){
            String stuno = data.getStringExtra("STUNO");
            String stuname = data.getStringExtra("NAME");
            int stuage = data.getIntExtra("AGE",0);

            Student student = new Student(stuno,stuname,stuage);
            addStudentToDB(student);
        }else if(resultCode == 3001){
            String stuno = data.getStringExtra("STUNO");
            String stuname = data.getStringExtra("NAME");
            int stuage = data.getIntExtra("AGE",0);

            Student student = new Student(stuno,stuname,stuage);
             updateStudentToDB(student);
        }
    }

    private void updateStudentToDB(Student student) {
        String path = getFilesDir().getAbsolutePath() + File.separator + "stu.db";
        SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(path,null);


        /*第一种放式，组装语句*/
         String sql = "update student set stuname ='"+student.getStuname()+"'," +
                 " stuage = "+student.getStuage()+" where stuno='"+student.getStuno()+"'";
         db.execSQL(sql);
         db.close();
        adapter.notifyDataSetChanged();
         readDataFromDB();

 /*第二种放式，update*/
/*       ContentValues values = contentValues;
       values.put("stuname",student.getStuname());
       values.put("stuage",student.getStuage());
       String where = "stuno= '"+student.getStuno()+"'";
       db.update("student",values,where,null);
            db.close();
            readDataFromDB();*/

    }

    private void addStudentToDB(Student student) {
        String path = getFilesDir().getAbsolutePath() + File.separator + "stu.db";
        SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(path,null);



        ContentValues values = new ContentValues();
        values.put("stuno",student.getStuno());
        values.put("stuname",student.getStuname());
        values.put("stuage",student.getStuage());


        db.insert("student",null,values);
        db.close();
        adapter.notifyDataSetChanged();
        readDataFromDB();



    }

    @Override
    public void del(Student student) {
        String path = getFilesDir().getAbsolutePath() + File.separator + "stu.db";
        SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(path,null);

        /*删除第一种方法*/
      /*   String sql = "delete from student where stuno='"+student.getStuno()+"'";
        db.execSQL(sql);
        db.close();
        adapter.notifyDataSetChanged();
        readDataFromDB();*/

       /*删除第二种方法*/
   /*   String where ="stuno ='" +student.getStuno() + "'";
      db.delete("student",where,null);
      db.close();
      adapter.notifyDataSetChanged();
      readDataFromDB();*/
 /*删除第三种方法*/
   String where = "stuno = ?";
   String[] argArray = {student.getStuno()};
   db.delete("student",where,argArray);
   db.close();
   adapter.notifyDataSetChanged();
   readDataFromDB();

    }
}
